//
//  HomeSubHotController.swift
//  KkmhSwift
//
//  Created by tenltrs on 2018/11/9.
//  Copyright © 2018 Tenltrs. All rights reserved.
//

import UIKit

protocol HomeSubHotControllerDelegate {
    
    func tableSlidingWithNavigation(hidden : Bool)
    
    func bottomClickForwardAction(_ vc : HomeSubHotController?)
}

class HomeSubHotController: BaseChildViewController,UITableViewDelegate,UITableViewDataSource,EmptyDataSetSource,EmptyDataSetDelegate {
    
    private var lastContentOffset : CGFloat = 0
    
    private var isNavRolling : Bool = true
    
    private var time : NSInteger?
    
    private var tableView : UITableView!
    
    var delegate : HomeSubHotControllerDelegate?
    
    private var isPulling = true  //是否为下拉
    
    var dataArray : [HomeAnimeModel] = []
    
    var pageIndex : NSInteger = 0
    
    var isRefresh = false
    
    init(with : NSInteger) {
        
        super.init(nibName: nil, bundle: nil)
        
        self.time = with
    
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        

        initData()
        
        initMain()
        
        let hud = HUDManager.loadShowing(to: self.view)
        hud.offset=CGPoint(x: 0, y: -150)
    }
    
    // MARK: -- 初始化数据
    func initData() {
        
        weak var ws = self
        
        RequestManager.GET(url: "\(RequestUrls.daily_comic_lists)/\(self.time!)", parameter: ["gender":App_Gender, "new_device":false, "since": pageIndex], target: self, isLoad: false, success: { (result) in
            HUDManager.loadHideing(from: self.view)
            ws?.tableView.mj_header?.endRefreshing()
            ws?.tableView.mj_footer?.endRefreshing()
            if result.success{
                let data = result.data as! [String : Any]
                let list = data["comics"] as! [[String : Any]]
                
                if ws?.isRefresh == true{
                    ws?.isRefresh=false
                    ws?.dataArray.removeAll()
                }

                for item in list{
                    let model = HomeAnimeModel.mj_object(withKeyValues: item)
                    ws?.dataArray.append(model!)
                }

                if list.count<20{
                    ws?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    ws?.tableView.tableFooterView=ws?.noDataFooterView
                }else{
                    ws?.tableView.tableFooterView=UIView()
                }
            }
            ws?.tableView.reloadData()
        }) { (error) in
            ws?.tableView.mj_header?.endRefreshing()
            ws?.tableView.mj_footer?.endRefreshing()
            HUDManager.loadHideing(from: self.view)
            
        }
        
    }

    // MARK: -- 初始化ui
    func initMain(){
        weak var ws = self
        tableView=UITableView.init(frame: CGRect.zero, style: .plain).then({ (make) in
            make.delegate=self
            make.dataSource=self
            make.register(cellType: HomeHotCell.self)
            make.contentInset=UIEdgeInsets(top: 0, left: 0, bottom:SafeAreaInsets.top+SafeAreaInsets.bottom+35, right: 0)
            make.showsVerticalScrollIndicator=false
            make.separatorStyle = UITableViewCell.SeparatorStyle.none
            make.backgroundColor=UIColor.BackgroundColor
            
            make.tableFooterView=UIView()
            
            make.emptyDataSetSource=self
            make.emptyDataSetDelegate=self
            
            //添加 加载刷新
            let refreshHeader = MJRefreshGifHeader.init(refreshingBlock: {
                ws?.isRefresh=true
                ws?.pageIndex=0
                ws?.initData()
            })
            
            let arr = [-15,-30,-45,-60,-75,-90,-105,-120,-135,-150,-165,-180,-195,-210,-225,-240,-255,-270,-285,-300,-315,-330,0]
            var imageArr = [UIImage]()
            for item in arr {
                imageArr.append(UIImage(named: "ic_pullrefresh_loading_17x17_")!.byRotate(DegreesToRadians(CGFloat(item)), fitSize: false)!)
            }
            
            refreshHeader?.setImages(imageArr, for:MJRefreshState.idle)
            refreshHeader?.lastUpdatedTimeLabel.isHidden=true
            refreshHeader?.stateLabel.isHidden=true
            make.mj_header=refreshHeader
            
            
            let refreshFooter = MJRefreshAutoNormalFooter.init(refreshingBlock: {
                ws?.pageIndex=(ws?.pageIndex)!+1
                ws?.initData()
            })
            refreshFooter?.stateLabel.isHidden=true
            refreshFooter?.isRefreshingTitleHidden=true
            make.mj_footer=refreshFooter
        })
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
    }
    
    // MARK: -- tableView代理
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell : HomeHotCell = tableView.dequeueReusableCell(for: indexPath)
        cell.fillData(model: dataArray[indexPath.row], indexPath: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = dataArray[indexPath.row]
        
        return HomeHotCell.hyb_height(for: tableView, config: { (cellSource) in
            
            let cell = cellSource as! HomeHotCell
            cell.fillData(model: model, indexPath: indexPath)
        }, cache: { () -> [AnyHashable : Any]? in
            return [kHYBCacheUniqueKey : model.id ?? "0",
                    kHYBCacheStateKey : "",
                    kHYBRecalculateForStateKey : false]
        })
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        if scrollView.contentOffset.y+scrollView.height > scrollView.contentSize.height || scrollView.contentOffset.y<0 {
            return
        }
        lastContentOffset = scrollView.contentOffset.y
        logger.info(lastContentOffset)
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if (scrollView.contentOffset.y > lastContentOffset+20 && self.navigationController?.isNavigationBarHidden == false){ //如果当前位移大于缓存位移，说明scrollView向上滑动
//            isPulling=false
            self.delegate?.tableSlidingWithNavigation(hidden: true)
        }else if(scrollView.contentOffset.y < lastContentOffset && self.navigationController?.isNavigationBarHidden == true){
//            isPulling=true
            self.delegate?.tableSlidingWithNavigation(hidden: false)
        }else if(scrollView.contentOffset.y<0){
//            isPulling=true
            self.delegate?.tableSlidingWithNavigation(hidden: false)
        }else{
            
        }        
    }
    
    // MARK: -- 空列表代理
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        
        return UIImage.init(named: "attention_empty_375x375_")
    }
    
    func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat {
        return -150
    }
    
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
        
        return true
    }
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
        return false
    }
    
    // MARK: -- 懒加载
    lazy var noDataFooterView : UIView = {
        weak var ws = self
        let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 105))
        
        let image : UIImage = UIImage(named: "comic_last_375x95_")!
        
        let imageView = UIImageView.init(frame: CGRect(x: (ScreenWidth-image.size.width)/2, y: (view.height-image.size.height)/2, width: image.size.width, height: image.size.height))
        imageView.image=image
        imageView.isUserInteractionEnabled=true
        imageView.ts_addTapAction({ (tap) in
            ws?.delegate?.bottomClickForwardAction(ws)
        })
        view.addSubview(imageView)
        
        return view
    }()
}
